/*
 * Copyright (C) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "download_interceptor_default.h"
#include "api/api_base.h"

namespace ImageKnifePro {

Rcp_Session *DownloadInterceptorDefault::GetRcpSession()
{
    std::lock_guard<std::mutex> guard(sessionLock_);
    if (sessionStack_.empty()) {
        uint32_t errorCode = 0;
        Rcp_Session *session = HMS_Rcp_CreateSession(NULL, &errorCode);
        if (!errorCode) {
            return session;
        }

        IMAGE_KNIFE_LOG(LOG_ERROR, "Rcp Create Session Failed, errorCode：%{public}d", errorCode);
        return nullptr;
    } else {
        Rcp_Session *session = sessionStack_.top();
        sessionStack_.pop();
        return session;
    }
}

void DownloadInterceptorDefault::RecycleSession(Rcp_Session *session)
{
    if (session == nullptr) {
        return;
    }

    std::lock_guard<std::mutex> guard(sessionLock_);
    sessionStack_.push(session);
}

void DownloadInterceptorDefault::DestroyConfiguration(Rcp_Request *rcpRequest)
{
    IMAGE_KNIFE_CHECK(rcpRequest == nullptr);
    if (rcpRequest->headers != nullptr) {
        HMS_Rcp_DestroyHeaders(rcpRequest->headers);
    }
    auto config = rcpRequest->configuration;
    if (config != nullptr) {
        if (config->securityConfiguration.certificate.filePath != nullptr) {
            free(config->securityConfiguration.certificate.filePath);
            config->securityConfiguration.certificate.filePath = nullptr;
        }
        delete config;
    }
    rcpRequest->configuration = nullptr;
}

bool DownloadInterceptorDefault::IsDownloadDetachEnabled()
{
    constexpr int minVersion = 13;
    static bool enable = ApiBase::GetApiVersion() > minVersion;

    return enable;
}

}

